package com.umeox.recorder

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.view.Window
import android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.core.content.res.ResourcesCompat
import com.umeox.moto.common.extension.mutableLiveDataOf
import com.umeox.moto.common.utils.GsonUtils
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import com.umeox.recorder.data.MediaManager
import com.umeox.recorder.data.RecorderBean
import com.umeox.recorder.databinding.ActivityRecordPlayBinding
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class RecordPlayActivity : ThemeAppCompatActivity() {
    private lateinit var mBinding: ActivityRecordPlayBinding
    private lateinit var mRecord: RecorderBean
    private lateinit var mMedia: MediaManager
    private lateinit var mBgPlay: Drawable
    private lateinit var mBgPause: Drawable
    private lateinit var mDeleteDialog: RecordDeleteDialog
    private var mMediaLength = 0
    private var mIsStopped = false

    //播放状态
    private var mIsPlaying: Boolean by mutableLiveDataOf(false) { onPlayStatus(it) }

    //文件播放进度毫秒值
    private var mPlayProgress: Int by mutableLiveDataOf(0) { onPlayProgress(it) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("lifecycle", "RecordPlayActivity#onCreate")

        mBinding = ActivityRecordPlayBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        mBinding.bar.setOnSeekBarChangeListener(SeekBarChangeListener())
        mBgPlay = ResourcesCompat.getDrawable(resources, R.drawable.recorder_icon_play, null)!!
        mBgPause = ResourcesCompat.getDrawable(resources, R.drawable.recorder_icon_pause, null)!!
        mDeleteDialog = RecordDeleteDialog(this) { finish() }

        //反序列化
        val data = intent.extras?.getString("data")
        if (data == null) {
            finish()
            return
        } else {
            mRecord = GsonUtils.toBean(data, RecorderBean::class.java)
        }

        //设置界面
        mBinding.tvName.text = File(mRecord.filePath).name
        mBinding.tvName.requestFocus()
        val date = Date(mRecord.createTime)
        val formater = SimpleDateFormat("yyyy/MM/dd", Locale.getDefault())
        mBinding.tvDate.text = formater.format(date)

        mMedia = MediaManager.instance
        mMedia.onProgress = {
            //观察到停止后会有一次进度回弹，原因不明，这里在停止后不再改变进度条
            if (!mIsStopped){
                mPlayProgress = it
                mBinding.bar.progress = it
            }
        }

        mMedia.onPlayComplete = {
            mIsPlaying = false
            mIsStopped = true
            mPlayProgress = mMediaLength
            mBinding.bar.progress = mMediaLength
        }

        mBinding.btnMain.setOnClickListener {
            val flag = mIsPlaying
            if (flag) mMedia.pause()
            else {
                if (mIsStopped) mMedia.setProgress(0)
                mMedia.play()
                mIsStopped = false
            }
            mIsPlaying = !flag
        }

        mBinding.btnVolume.setOnClickListener {
            mMedia.pause()
            mIsPlaying = false
            val intent = Intent(this, VolumeActivity::class.java)
            startActivity(intent)
        }

        mBinding.btnDelete.setOnClickListener {
            mMedia.pause()
            mIsPlaying = false
            mDeleteDialog.show(mRecord)
        }
    }

    private var pausedProgress: Int? = null
    override fun onPause() {
        super.onPause()
        Log.d("lifecycle", "RecordPlayActivity#onPause")
        if (mIsPlaying){
            mMedia.pause()
            mIsPlaying = false
        }
        pausedProgress = mMedia.getProgress()
    }

    override fun onResume() {
        super.onResume()
        Log.d("lifecycle", "RecordPlayActivity#onResume")
        //离开Activity可能造成Prepare失效，放到resume来操作。
        mMedia.prepare(mRecord.filePath) {
            val length = mMedia.getLength()
            mMediaLength = length
            mBinding.bar.max = length
            mBinding.tvBarMax.text = if (mMediaLength > 0) getTimeStr(mMediaLength) else getTimeStr(0)
            pausedProgress?.let {
                mMedia.setProgress(it)
            }
        }
    }

    private fun onPlayStatus(play: Boolean) {
        if (play) {
            mBinding.btnMain.background = mBgPause
            window.addFlags(FLAG_KEEP_SCREEN_ON)
        } else {
            mBinding.btnMain.background = mBgPlay
            window.clearFlags(FLAG_KEEP_SCREEN_ON)
        }
    }

    private fun onPlayProgress(progress: Int) {
        if (mMediaLength != 0) {
            mBinding.tvBarCurrent.text = getTimeStr(progress)
        }
    }

    private inner class SeekBarChangeListener : OnSeekBarChangeListener {
        override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
            if (!fromUser) return
            if (mMediaLength != 0) {
                mPlayProgress = progress
            }
        }

        override fun onStartTrackingTouch(seekBar: SeekBar) {
            if (mIsPlaying) {
                mMedia.pause()
                mIsPlaying = false
            }
        }

        override fun onStopTrackingTouch(seekBar: SeekBar) {
            mMedia.setProgress(mPlayProgress)
            mMedia.play()
            mIsStopped = false
            mIsPlaying = true
        }

    }

    override fun onStart() {
        super.onStart()
        Log.d("lifecycle", "RecordPlayActivity#onStart")
    }

    override fun onStop() {
        super.onStop()
        Log.d("lifecycle", "RecordPlayActivity#onStop")
    }
    override fun onDestroy() {
        super.onDestroy()
        Log.d("lifecycle", "RecordPlayActivity#onDestroy")
        mMedia.release()
    }

    @SuppressLint("DefaultLocale")
    private fun getTimeStr(millis: Int): String {
        val secondTime = millis / 1000
        val second = secondTime % 60
        val minute = secondTime / 60
        return "${String.format("%02d", minute)}:${String.format("%02d", second)}"
    }
}
